import createAction from './createAction'
import createReducer from './createReducer'
/**
 * 创建一个带有 reducer 处理函数的对象\
 * 会根据列出的 reducer 的名称自动生成 action type 字符串 和 action creator 函数\
 */
function createSlice(options) {
  const {
    name, // slice 分片名称 同时也会为每个 action.type 动作对象的类型添加 分片名称/ 前缀
    initialState = {}, // slice 分片的初始状态
    reducers = {}, // 一个对象 其键是 action 类型 值是 reducer 处理函数
  } = options

  const prefixedReducers = {}
  const actions = {}
  Object.keys(reducers).forEach(key => {
    const type = `${name}/${key}`
    // 添加前缀
    prefixedReducers[type] = reducers[key] // prefixedReducers['counter1/add']=reducer
    actions[key] = createAction(type) // actions.add = () => {return {type: "add"} }
  })

  // 将 reducers 对象中的每个子 reducer 处理函数合并成一个 reducer 处理函数
  const reducer = createReducer(initialState, prefixedReducers)

  return {
    name,
    reducerPath: name,
    reducer,
    actions
  }
}

export default createSlice
